package com.hl.mystudy.ui.home.ui.viewpager;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager.widget.PagerAdapter;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.hl.mystudy.R;
import com.hl.mystudy.databinding.ActivityViewPagerLoadViewBinding;
import com.hl.mystudy.util.LogUtil;

import java.util.List;

public class ViewPagerLoadViewActivity extends AppCompatActivity {

    private Context mContext;
    private ActivityViewPagerLoadViewBinding mBinding;
    private ViewPagerLoadViewModel mModel;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_view_pager_load_view);
        mModel = new ViewModelProvider(this).get(ViewPagerLoadViewModel.class);
        mModel.getPicUrlListLive().observe(this, strings -> {
            LogUtil.i("数据改变");
        });

        mBinding.vpLoadView.setAdapter(new LoadViewAdapter(mModel.getTestData()));
    }

    private class LoadViewAdapter extends PagerAdapter {
        private List<String> mDataList;
        public LoadViewAdapter(List<String> picUrlList) {
            mDataList = picUrlList;
        }

        @Override
        public int getCount() {
            return mDataList.size();
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            //加载vp的布局
            View inflate = View.inflate(container.getContext(), R.layout.item_fragment_home_rv_item, null);
            //给布局控件赋值
            TextView textView = inflate.findViewById(R.id.tv_item);
            textView.setText(mDataList.get(position));
            //添加一个布局（不添加无效果）
            container.addView(inflate);
            return inflate;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            //移除视图
            container.removeView((View) object);
        }
    }
}